package com.raghu;

import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class MTS {

	private List<Transaction> list;
	
	public MTS(){
		this.list = new LinkedList<Transaction>();
	}
	
	public void insert(Transaction t){
		int i=0;
		for(Iterator<Transaction> it = list.iterator();it.hasNext();i++)
		{
			if(t.getTime()>it.next().getTime())
				break;
			i++;
		}
		list.add(i, t);
	}
	
	public void insert(int time,String location,Set<String> service){
		int i=0;
		for(Iterator<Transaction> it = list.iterator();it.hasNext();i++)
		{
			if(time>it.next().getTime())
				break;
			i++;
			
		}
		list.add(i,new Transaction(time,location,service));
	}
	
	public Iterator<Transaction> iterator(){
		return list.iterator();
	}
	
	public int length(){
		return list.size();
	}
	
	public Transaction getTransaction(int index){
		return list.get(index);
	}
	
	private double max(double a,double b,double c){
		if(a>=b && a>=c)
			return a;
		else if(b>=a && b>=c )
			return b;
		else
			return c;
	}
	
	private double max(double a, double b) {
		if(a>b)
			return a;
		else
			return b;
		
	}
	
	public double similarity(MTS s1){
		MTS s=this;
		double[][] m = new double[s.length()+1][s1.length()+1];
		double p=0.5/(s.length()+s1.length());
		m[0][0]=0.5;
		for(int i=1;i<=s.length();i++)
			m[i][0]=m[i-1][0]-p;
		for(int j=1;j<=s1.length();j++)
			m[0][j]=m[0][j-1]-p;
		for(int i=1;i<=s.length();i++)
		{
			for(int j=1;j<=s1.length();j++)
			{
				if(s.getTransaction(i-1).getLocation().equals(s1.getTransaction(j-1).getLocation()))
				{
					double temp=s.getTransaction(i-1).getTime()-s1.getTransaction(j-1).getTime();
					if(temp<0)
						temp=temp*(-1);
					double tp=p*temp;
					Set<String> intersection = new HashSet<String>(s.getTransaction(i-1).getService());
					intersection.retainAll(s1.getTransaction(j-1).getService());
					Set<String> union = new HashSet<String>(s.getTransaction(i-1).getService());
					union.addAll(s1.getTransaction(j-1).getService());
					double sr = p*((double)intersection.size()/(double)union.size());
					m[i][j] = max(m[i-1][j-1]-tp+sr, m[i-1][j]-p,m[i][j-1]-p);
				}
				else
				{
					m[i][j] = max(m[i-1][j]-p,m[i][j-1]-p);
				}
			}
		}
		return m[s.length()][s1.length()];
	}
}
